# 某视频网站缓存的视频和音频的合并的批量处理py脚本

from asyncio.windows_events import NULL
import os
from pathlib import Path
from multiprocessing import Process
import time
import json

# 合并工具
global mergetools
# 合并工具命令行模式下的合并参数 -o 输出文件 输入视频 输入音频
template = """ -o "{}" "{}" "{}" """
# 输出文件的命名方式
outname = "{} {}.mkv"
# 全局日志文件
global f
# 日志文件名
logF = "merge.log"
global argss
argss=[]

def initlog(dir):
    # 添加日志文件
    log = os.path.join(dir, logF)
    if os.path.exists(log):
        os.remove(log)
    global f
    f = os.open(log, os.O_RDWR | os.O_CREAT)
    pass


def endlog():
    os.close(f)
    pass


def wlog(msg):
    os.write(f, str.encode(msg))
    os.write(f, str.encode("\n"))
    print(msg)
    pass


def runmerge(dir):
    if not os.path.exists(dir):
        wlog("目录:【" + dir + "】不存在!!")
        return
    mdir = Path(dir)
    if not mdir.is_dir():
        wlog("目录【" + dir + "】不是一个目录!!")
        return
    # 遍历子目录 解析分视频目录
    subdirs = []
    for mdir, subdir, file_list in os.walk(mdir):
        for d in subdir:
            subdirs.append(d)
        break
    i = 1
    global argss
    argss=[]
    for d in subdirs:
        ddir0 = os.path.join(dir, d)
        ddirss =set()
        tempstr=NULL
        for t in {"80","64","32","16"}:
            ddirss.add(os.path.join(ddir0, t))
            # tempstr=tempstr+ "["+t +"]"
        # ddirss ={os.path.join(ddir0, "80"),os.path.join(ddir0, "64"),os.path.join(ddir0, "32"),os.path.join(ddir0, "16")}
        ddir = None
        for d1 in ddirss:
            if os.path.exists(d1):
                ddir = d1
                break
        if ddir is None:
            # wlog("目录不存在:" + ddir0 + "\\[80][64][32|16]")
            wlog("目录不存在:" + ddir0 + "\\"+tempstr)
            continue
        video = os.path.join(ddir, "video.m4s")
        audio = os.path.join(ddir, "audio.m4s")
        if not os.path.exists(video):
            wlog("视频文件不存在:" + video)
            continue
        if not os.path.exists(audio):
            wlog("音频文件不存在:" + audio)
            continue
        title = None
        name = None
        # 读取视频信息 json方式存储
        jfile = os.path.join(dir, d, "entry.json")
        if os.path.exists(jfile):
            fjson = open(jfile, "r", encoding="utf-8").read()
            data = json.loads(fjson)
            if "title" in data:
                title = data["title"]
            if "page_data" in data:
                if "part" in data["page_data"]:
                    name = data["page_data"]["part"]
        if name == None:
            name = i
        else:
            name = name.replace("/", "_")
            name = name.replace("\\", "_")
        # 对标题中的特殊字符进行转义避免与文件命名规则冲突
        title = title.replace("/", "_")
        title = title.replace("\\", "_")
        title = title.replace("【", "[")
        title = title.replace("】", "]")
        outname1 = outname.format(title, name).replace('  ',' ').replace('-','_')
        outf = os.path.join(dir, outname1)
        # 生成执行参数
        args = template.format(outf, video, audio)
        # 生成执行命令
        argss.append(mergetools + args)
        i = i + 1
        wlog(mergetools + args)
    pass

def mergeVA(argss):
    # 使用第三方工具合并视频
    for arg in argss:
        # 启动第三方进程开始合并
        os.popen(arg)
        time.sleep(3)
    pass

if __name__ == "__main__":
    # dirs = {"E:\素材\Temp\计算机图形学\\15129423","E:\素材\Temp\计算机图形学\\66548502","E:\素材\Temp\数学\\88073270","E:\素材\Temp\数学\\670086601"}
    # dirs = {"E:\素材\Temp\计算机图形学\\15129423"}
    dirs = {"E:\素材\Temp\\377290716"}
    mergetools = """E:\小丸工具箱\\tools\mkvmerge.exe"""
    for dir in dirs:
        initlog(dir)
        runmerge(dir)
        mergeVA(argss)
    print("处理完成")
    endlog()
    pass
